<template>
  <div class="batch-quality-score-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>批量计算质量分</span>
        </div>
      </template>
      <div class="card-content">
        <!-- 输入表单组件 -->
        <BatchInputForm 
          :processing="processing"
          @start-process="startBatchProcess"
          @clear-results="clearResults"
        />

        <!-- 结果列表区域 -->
        <div class="result-section">
          <el-divider content-position="center">处理结果</el-divider>
          
          <!-- 进度指示器组件 -->
          <BatchProgressIndicator 
            :processing="processing"
            :progress-percentage="progressPercentage"
            :current-process-index="currentProcessIndex"
            :total-process-count="totalProcessCount"
            :processing-summary="processingSummary"
          />
          
          <!-- 结果表格组件 -->
          <div class="result-table-wrapper">
            <BatchResultTable 
              :result-list="resultList"
              :processing="processing"
              @show-detail="showScoreDetail"
            />
          </div>
          
          <!-- 错误统计组件 -->
          <div class="error-statistics-wrapper">
            <BatchErrorStatistics 
              :error-statistics="errorStatistics"
            />
          </div>
        </div>

        <!-- 错误提示 -->
        <el-alert
          v-if="errorMessage"
          :title="errorMessage"
          type="error"
          show-icon
          :closable="true"
          @close="errorMessage = ''"
        ></el-alert>
      </div>
    </el-card>

    <!-- 质量分详情对话框组件 -->
    <QualityScoreDetail 
      v-model:dialog-visible="detailDialogVisible"
      :score-detail="currentScoreDetail"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { getResumeList } from '@/api/resumeList'
import { calculateQualityScore, QualityScoreResult, DetailItem } from '@/api/resume'

// 导入拆分的组件
import BatchInputForm from '@/components/BatchQuality/BatchInputForm.vue'
import BatchProgressIndicator from '@/components/BatchQuality/BatchProgressIndicator.vue'
import BatchResultTable from '@/components/BatchQuality/BatchResultTable.vue'
import BatchErrorStatistics from '@/components/BatchQuality/BatchErrorStatistics.vue'
import QualityScoreDetail from '@/components/BatchQuality/QualityScoreDetail.vue'

// 定义结果项接口
interface ResultItem {
  userId: string
  resumeNumber: string
  score: string
  status: string
  scoreResult: QualityScoreResult | null
  errors: DetailItem[]
}

// 定义错误统计项接口
interface ErrorStatItem {
  errorCode: string
  count: number
  description: string
}

const processing = ref(false)
const resultList = ref<ResultItem[]>([])
const errorMessage = ref('')
const errorStatistics = ref<ErrorStatItem[]>([])
const detailDialogVisible = ref(false)
const currentScoreDetail = ref<QualityScoreResult | null>(null)

// 进度相关
const currentProcessIndex = ref(0)
const totalProcessCount = ref(0)
const successCount = ref(0)
const failCount = ref(0)
const noResumeCount = ref(0)
const progressPercentage = ref(0)
const processingSummary = ref('')

// 开始批量处理
const startBatchProcess = async (userIds: string[]) => {
  if (userIds.length === 0) {
    errorMessage.value = '请输入至少一个用户ID'
    return
  }

  processing.value = true
  errorMessage.value = ''
  resultList.value = []
  errorStatistics.value = []
  
  // 重置进度相关数据
  currentProcessIndex.value = 0
  successCount.value = 0
  failCount.value = 0
  noResumeCount.value = 0
  progressPercentage.value = 0
  processingSummary.value = ''
  
  // 设置总处理数量
  totalProcessCount.value = userIds.length
  
  // 为每个用户ID创建一个初始结果项
  resultList.value = userIds.map(userId => ({
    userId,
    resumeNumber: '',
    score: '',
    status: '处理中',
    scoreResult: null,
    errors: []
  }))

  // 逐个处理每个用户ID
  for (let i = 0; i < resultList.value.length; i++) {
    const item = resultList.value[i]
    
    // 更新当前处理索引和进度百分比
    currentProcessIndex.value = i + 1
    progressPercentage.value = Math.floor((currentProcessIndex.value / totalProcessCount.value) * 100)
    
    try {
      // 1. 获取简历列表
      const resumeListResponse = await getResumeList({
        userid: parseInt(item.userId),
        lang: 1 // 假设1代表中文
      })
      
      // 检查是否有简历
      if (resumeListResponse.data.length === 0) {
        item.status = '无简历'
        noResumeCount.value++
        continue
      }
      
      // 2. 获取第一个简历的编号
      const firstResume = resumeListResponse.data[0]
      item.resumeNumber = firstResume.resumeNumber
      
      // 3. 调用质量评分接口
      const scoreResponse = await calculateQualityScore({
        resumeNumber: item.resumeNumber,
        userId: item.userId
      })
      
      // 4. 更新结果
      item.score = scoreResponse.data.totalScore
      item.status = '完成'
      item.scoreResult = scoreResponse.data
      successCount.value++
      
      // 5. 收集错误信息
      const errors: DetailItem[] = []
      scoreResponse.data.detailList.forEach(category => {
        category.moduleGroupList.forEach(moduleGroup => {
          errors.push(...moduleGroup.detailList)
        })
      })
      item.errors = errors
      
    } catch (error) {
      console.error('处理用户ID时出错:', item.userId, error)
      item.status = '失败'
      failCount.value++
    }
  }
  
  // 处理完成后，统计错误
  calculateErrorStatistics()
  
  // 生成处理结果摘要
  processingSummary.value = `处理完成：共处理 ${totalProcessCount.value} 个用户ID，成功 ${successCount.value} 个，失败 ${failCount.value} 个，无简历 ${noResumeCount.value} 个`
  
  processing.value = false
  progressPercentage.value = 0
  currentProcessIndex.value = 0
}

// 计算错误统计
const calculateErrorStatistics = () => {
  const errorMap = new Map<string, { count: number, description: string }>()
  
  resultList.value.forEach(item => {
    if (item.errors && item.errors.length > 0) {
      item.errors.forEach(error => {
        const key = error.errorCode
        if (errorMap.has(key)) {
          const current = errorMap.get(key)!
          current.count++
          errorMap.set(key, current)
        } else {
          errorMap.set(key, { count: 1, description: error.detailDesc })
        }
      })
    }
  })
  
  errorStatistics.value = Array.from(errorMap.entries()).map(([errorCode, data]) => ({
    errorCode,
    count: data.count,
    description: data.description
  })).sort((a, b) => b.count - a.count)
}

// 清空结果
const clearResults = () => {
  resultList.value = []
  errorStatistics.value = []
  processingSummary.value = ''
}

// 显示质量分详情
const showScoreDetail = (row: ResultItem) => {
  currentScoreDetail.value = row.scoreResult
  detailDialogVisible.value = true
}
</script>

<style scoped>
.batch-quality-score-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-content {
  padding: 20px 0;
}

.result-section {
  margin-top: 20px;
}

.result-table-wrapper {
  margin-top: 20px;
  width: 100%;
}

.error-statistics-wrapper {
  margin-top: 20px;
  width: 100%;
}
</style>